import { useState, useEffect, useCallback } from 'react';

type SetValue<T> = T | ((val: T) => T);

export function useLocalStorage<T>(
  key: string,
  initialValue: T
): [T, (value: SetValue<T>) => void, () => void] {
  // 状态存储我们的值
  const [storedValue, setStoredValue] = useState<T>(initialValue);

  // 获取localStorage值的函数
  const getValue = useCallback((): T => {
    if (typeof window === 'undefined') {
      return initialValue;
    }

    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.warn(`Error reading localStorage key "${key}":`, error);
      return initialValue;
    }
  }, [key, initialValue]);

  // 在组件挂载时获取初始值
  useEffect(() => {
    setStoredValue(getValue());
  }, [getValue]);

  // 设置值的函数
  const setValue = useCallback(
    (value: SetValue<T>) => {
      try {
        // 允许值是函数，这样我们就有了和useState相同的API
        const valueToStore =
          value instanceof Function ? value(storedValue) : value;

        // 保存到状态
        setStoredValue(valueToStore);

        // 保存到localStorage
        if (typeof window !== 'undefined') {
          window.localStorage.setItem(key, JSON.stringify(valueToStore));
        }
      } catch (error) {
        console.warn(`Error setting localStorage key "${key}":`, error);
      }
    },
    [key, storedValue]
  );

  // 删除值的函数
  const removeValue = useCallback(() => {
    try {
      setStoredValue(initialValue);
      if (typeof window !== 'undefined') {
        window.localStorage.removeItem(key);
      }
    } catch (error) {
      console.warn(`Error removing localStorage key "${key}":`, error);
    }
  }, [key, initialValue]);

  return [storedValue, setValue, removeValue];
}
